package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisConfig implements BeanPostProcessor {

	protected static final Logger log = LoggerFactory.getLogger(RedisConfig.class);
	
	public static String REDIS_HOST_KEY = "redis.host";
	public static String REDIS_PORT_KEY = "redis.port";
	
	private static JedisPool pool;
	
	@Value("${redis.host}")
	private String host;
	@Value("${redis.port}")
	private int port;
	
//	@PostConstruct
//	public void apolloListener() {
//		// Config config = ConfigService.getConfig("FX.Hermes.Producer");
//		ConfigService.getConfig("TEST3.cps-server").addChangeListener(new ConfigChangeListener() {
//			@Override
//			public void onChange(ConfigChangeEvent changeEvent) {
//				boolean flag = false;
//				for(String key : changeEvent.changedKeys()) {
//					if(REDIS_PORT_KEY.equals(key) ||  REDIS_HOST_KEY.equals(key)) {
//						flag = true;
//					} 
//					log.info("onChange key = {}", key);
//				}
//				if (flag) {
//					init();
//				}
//			}
//		});
//	}
	
	private void init() {
		pool = new JedisPool(host, port);
		log.info("init {}", "初始化redis 链接池。。。");
	}
	
	@ApolloConfigChangeListener(
			value = {ConfigConsts.NAMESPACE_APPLICATION, "TEST3.cps-server"}
			, interestedKeys = {"redis.host", "redis.port"})
	private void changeRedis(ConfigChangeEvent changeEvent) {
		init();
	}
	
	public  Jedis getJedis() {
		if(pool == null)
			init();
		return pool.getResource();
	}

//	@Override
//	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//		apolloListener();
//		return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
//	}
	
	
}
